<template>
  <div class="wallet-page">
    <van-nav-bar
      title="钱包"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />
    
    <div class="wallet-content">
      <!-- 账户余额卡片 -->
      <div class="balance-card">
        <div class="card-header">
          <span>账户余额</span>
          <van-icon name="eye-o" @click="toggleBalanceVisible" v-if="isBalanceVisible" />
          <van-icon name="closed-eye" @click="toggleBalanceVisible" v-else />
        </div>
        <div class="balance-amount">
          <span class="currency">¥</span>
          <span class="amount" v-if="isBalanceVisible">{{ formatAmount(accountBalance) }}</span>
          <span class="amount" v-else>****</span>
        </div>
        <div class="card-actions">
          <div class="action-button" @click="showRechargePopup = true">
            <van-icon name="plus" />
            <span>充值</span>
          </div>
          <div class="action-button" @click="showWithdrawPopup = true">
            <van-icon name="minus" />
            <span>提现</span>
          </div>
          <div class="action-button" @click="navigateTo('/wallet/transfer')">
            <van-icon name="exchange" />
            <span>转账</span>
          </div>
        </div>
      </div>
      
      <!-- 快捷功能 -->
      <div class="quick-actions">
        <div class="action-item" @click="navigateTo('/wallet/bills')">
          <van-icon name="notes-o" size="24" />
          <span>账单</span>
        </div>
        <div class="action-item" @click="navigateTo('/wallet/cards')">
          <van-icon name="credit-pay" size="24" />
          <span>银行卡</span>
        </div>
        <div class="action-item" @click="navigateTo('/wallet/rewards')">
          <van-icon name="gift-o" size="24" />
          <span>奖励</span>
        </div>
        <div class="action-item" @click="navigateTo('/wallet/settings')">
          <van-icon name="setting-o" size="24" />
          <span>设置</span>
        </div>
      </div>
      
      <!-- 交易记录 -->
      <div class="transaction-section">
        <div class="section-header">
          <span>近期交易</span>
          <span class="view-all" @click="navigateTo('/wallet/bills')">查看全部</span>
        </div>
        
        <div class="transaction-list">
          <div v-if="transactions.length > 0">
            <div 
              v-for="(item, index) in transactions" 
              :key="index" 
              class="transaction-item"
              @click="showTransactionDetail(item)"
            >
              <div class="transaction-icon" :class="getTransactionClass(item.type)">
                <van-icon :name="getTransactionIcon(item.type)" />
              </div>
              <div class="transaction-info">
                <div class="transaction-title">{{ item.title }}</div>
                <div class="transaction-time">{{ item.time }}</div>
              </div>
              <div class="transaction-amount" :class="{ 'amount-positive': item.amount > 0, 'amount-negative': item.amount < 0 }">
                {{ item.amount > 0 ? '+' : '' }}{{ formatAmount(item.amount) }}
              </div>
            </div>
          </div>
          <div v-else class="empty-state">
            <van-empty description="暂无交易记录" />
          </div>
        </div>
      </div>
    </div>
    
    <!-- 充值弹窗 -->
    <van-popup v-model:show="showRechargePopup" round :style="{ width: '90%' }">
      <div class="popup-content">
        <div class="popup-header">
          <span>充值</span>
          <van-icon name="cross" @click="showRechargePopup = false" />
        </div>
        
        <div class="popup-form">
          <van-field
            v-model="rechargeAmount"
            type="digit"
            label="充值金额"
            placeholder="请输入充值金额"
          />
          
          <div class="quick-amounts">
            <div 
              v-for="(amount, index) in quickAmounts" 
              :key="index" 
              class="amount-tag"
              :class="{ active: rechargeAmount === amount.toString() }"
              @click="rechargeAmount = amount.toString()"
            >
              {{ amount }}元
            </div>
          </div>
          
          <div class="payment-methods">
            <div class="method-title">支付方式</div>
            <div 
              v-for="(method, index) in paymentMethods" 
              :key="index" 
              class="payment-method"
              :class="{ active: selectedPaymentMethod === method.id }"
              @click="selectedPaymentMethod = method.id"
            >
              <div class="method-icon">
                <van-icon :name="method.icon" />
              </div>
              <div class="method-name">{{ method.name }}</div>
              <div class="method-check">
                <van-icon name="success" v-if="selectedPaymentMethod === method.id" />
              </div>
            </div>
          </div>
          
          <div class="popup-actions">
            <van-button type="primary" block @click="handleRecharge">确认充值</van-button>
          </div>
        </div>
      </div>
    </van-popup>
    
    <!-- 提现弹窗 -->
    <van-popup v-model:show="showWithdrawPopup" round :style="{ width: '90%' }">
      <div class="popup-content">
        <div class="popup-header">
          <span>提现</span>
          <van-icon name="cross" @click="showWithdrawPopup = false" />
        </div>
        
        <div class="popup-form">
          <van-field
            v-model="withdrawAmount"
            type="digit"
            label="提现金额"
            placeholder="请输入提现金额"
          />
          
          <div class="withdraw-info">
            <div class="info-item">
              <span>可提现余额</span>
              <span>{{ formatAmount(accountBalance) }}元</span>
            </div>
            <div class="info-item">
              <span>手续费</span>
              <span>{{ calculateFee(withdrawAmount) }}元</span>
            </div>
            <div class="info-item">
              <span>实际到账</span>
              <span>{{ calculateActual(withdrawAmount) }}元</span>
            </div>
          </div>
          
          <div class="withdraw-to">
            <div class="method-title">提现到</div>
            <div 
              v-for="(card, index) in bankCards" 
              :key="index" 
              class="bank-card"
              :class="{ active: selectedBankCard === card.id }"
              @click="selectedBankCard = card.id"
            >
              <div class="card-icon">
                <van-icon :name="card.icon" />
              </div>
              <div class="card-info">
                <div class="card-name">{{ card.bank }}</div>
                <div class="card-number">{{ card.number }}</div>
              </div>
              <div class="card-check">
                <van-icon name="success" v-if="selectedBankCard === card.id" />
              </div>
            </div>
          </div>
          
          <div class="popup-actions">
            <van-button type="primary" block @click="handleWithdraw">确认提现</van-button>
          </div>
        </div>
      </div>
    </van-popup>
    
    <!-- 交易详情弹窗 -->
    <van-popup v-model:show="showTransactionDetailPopup" round :style="{ width: '90%' }">
      <div class="popup-content">
        <div class="popup-header">
          <span>交易详情</span>
          <van-icon name="cross" @click="showTransactionDetailPopup = false" />
        </div>
        
        <div class="transaction-detail">
          <div class="detail-amount" :class="{ 'amount-positive': currentTransaction.amount > 0, 'amount-negative': currentTransaction.amount < 0 }">
            {{ currentTransaction.amount > 0 ? '+' : '' }}{{ formatAmount(currentTransaction.amount) }}
          </div>
          
          <div class="detail-status">
            <van-tag type="success" v-if="currentTransaction.status === 'success'">交易成功</van-tag>
            <van-tag type="warning" v-else-if="currentTransaction.status === 'pending'">处理中</van-tag>
            <van-tag type="danger" v-else>交易失败</van-tag>
          </div>
          
          <div class="detail-items">
            <div class="detail-item">
              <span class="item-label">交易类型</span>
              <span class="item-value">{{ getTransactionTypeName(currentTransaction.type) }}</span>
            </div>
            <div class="detail-item">
              <span class="item-label">交易时间</span>
              <span class="item-value">{{ currentTransaction.time }}</span>
            </div>
            <div class="detail-item">
              <span class="item-label">交易单号</span>
              <span class="item-value">{{ currentTransaction.id || '-' }}</span>
            </div>
            <div class="detail-item">
              <span class="item-label">备注</span>
              <span class="item-value">{{ currentTransaction.remark || '无' }}</span>
            </div>
          </div>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'

const router = useRouter()

// 账户余额
const accountBalance = ref(1234.56)
const isBalanceVisible = ref(true)

// 弹窗控制
const showRechargePopup = ref(false)
const showWithdrawPopup = ref(false)
const showTransactionDetailPopup = ref(false)

// 充值相关
const rechargeAmount = ref('')
const quickAmounts = [50, 100, 200, 500]
const selectedPaymentMethod = ref('alipay')
const paymentMethods = [
  { id: 'alipay', name: '支付宝', icon: 'alipay' },
  { id: 'wechat', name: '微信支付', icon: 'wechat-pay' },
  { id: 'card', name: '银行卡', icon: 'credit-pay' }
]

// 提现相关
const withdrawAmount = ref('')
const selectedBankCard = ref('card1')
const bankCards = [
  { id: 'card1', bank: '工商银行', number: '**** **** **** 1234', icon: 'credit-pay' },
  { id: 'card2', bank: '建设银行', number: '**** **** **** 5678', icon: 'credit-pay' }
]

// 交易记录
const transactions = ref([
  { id: 'T20230601001', title: '充值', amount: 100, type: 'recharge', time: '2023-06-01 14:30', status: 'success', remark: '支付宝充值' },
  { id: 'T20230530002', title: '购买商品', amount: -45.5, type: 'payment', time: '2023-05-30 10:15', status: 'success', remark: '购买日用品' },
  { id: 'T20230525003', title: '提现', amount: -200, type: 'withdraw', time: '2023-05-25 16:20', status: 'success', remark: '提现到工商银行' },
  { id: 'T20230520004', title: '转账-张三', amount: -100, type: 'transfer', time: '2023-05-20 09:45', status: 'success', remark: '生日礼物' },
  { id: 'T20230515005', title: '退款', amount: 30, type: 'refund', time: '2023-05-15 11:30', status: 'success', remark: '商品退款' }
])

// 当前查看的交易详情
const currentTransaction = ref({})

// 返回上一页
const onClickLeft = () => {
  router.back()
}

// 切换余额显示
const toggleBalanceVisible = () => {
  isBalanceVisible.value = !isBalanceVisible.value
}

// 导航到指定路径
const navigateTo = (path) => {
  router.push(path)
}

// 格式化金额
const formatAmount = (amount) => {
  return parseFloat(amount).toFixed(2)
}

// 计算提现手续费
const calculateFee = (amount) => {
  if (!amount) return '0.00'
  const fee = parseFloat(amount) * 0.01 // 1%手续费
  return fee.toFixed(2)
}

// 计算实际到账金额
const calculateActual = (amount) => {
  if (!amount) return '0.00'
  const fee = parseFloat(amount) * 0.01
  const actual = parseFloat(amount) - fee
  return actual > 0 ? actual.toFixed(2) : '0.00'
}

// 处理充值
const handleRecharge = () => {
  if (!rechargeAmount.value) {
    showToast('请输入充值金额')
    return
  }
  
  const amount = parseFloat(rechargeAmount.value)
  if (isNaN(amount) || amount <= 0) {
    showToast('请输入有效金额')
    return
  }
  
  showToast('充值处理中...')
  
  // 模拟充值成功
  setTimeout(() => {
    accountBalance.value += amount
    showToast('充值成功')
    showRechargePopup.value = false
    rechargeAmount.value = ''
    
    // 添加交易记录
    const newTransaction = {
      id: `T${Date.now()}`,
      title: '充值',
      amount: amount,
      type: 'recharge',
      time: new Date().toLocaleString(),
      status: 'success',
      remark: `${getPaymentMethodName(selectedPaymentMethod.value)}充值`
    }
    
    transactions.value.unshift(newTransaction)
  }, 1500)
}

// 处理提现
const handleWithdraw = () => {
  if (!withdrawAmount.value) {
    showToast('请输入提现金额')
    return
  }
  
  const amount = parseFloat(withdrawAmount.value)
  if (isNaN(amount) || amount <= 0) {
    showToast('请输入有效金额')
    return
  }
  
  if (amount > accountBalance.value) {
    showToast('余额不足')
    return
  }
  
  showToast('提现处理中...')
  
  // 模拟提现成功
  setTimeout(() => {
    accountBalance.value -= amount
    showToast('提现申请已提交')
    showWithdrawPopup.value = false
    withdrawAmount.value = ''
    
    // 添加交易记录
    const newTransaction = {
      id: `T${Date.now()}`,
      title: '提现',
      amount: -amount,
      type: 'withdraw',
      time: new Date().toLocaleString(),
      status: 'pending',
      remark: `提现到${getBankCardName(selectedBankCard.value)}`
    }
    
    transactions.value.unshift(newTransaction)
  }, 1500)
}

// 显示交易详情
const showTransactionDetail = (transaction) => {
  currentTransaction.value = transaction
  showTransactionDetailPopup.value = true
}

// 获取交易图标
const getTransactionIcon = (type) => {
  const iconMap = {
    recharge: 'plus',
    withdraw: 'minus',
    transfer: 'exchange',
    payment: 'shopping-cart-o',
    refund: 'replay'
  }
  
  return iconMap[type] || 'balance-o'
}

// 获取交易类型样式
const getTransactionClass = (type) => {
  const classMap = {
    recharge: 'icon-recharge',
    withdraw: 'icon-withdraw',
    transfer: 'icon-transfer',
    payment: 'icon-payment',
    refund: 'icon-refund'
  }
  
  return classMap[type] || ''
}

// 获取交易类型名称
const getTransactionTypeName = (type) => {
  const nameMap = {
    recharge: '充值',
    withdraw: '提现',
    transfer: '转账',
    payment: '支付',
    refund: '退款'
  }
  
  return nameMap[type] || '其他'
}

// 获取支付方式名称
const getPaymentMethodName = (id) => {
  const method = paymentMethods.find(m => m.id === id)
  return method ? method.name : '未知'
}

// 获取银行卡名称
const getBankCardName = (id) => {
  const card = bankCards.find(c => c.id === id)
  return card ? card.bank : '未知'
}
</script>

<style lang="scss" scoped>
.wallet-page {
  min-height: 100vh;
  background-color: var(--background-color);
  padding-bottom: calc(var(--tabbar-height) + 20px);
  
  .wallet-content {
    padding: 16px;
    
    .balance-card {
      background: linear-gradient(135deg, var(--primary-color), #4a66f7);
      border-radius: 12px;
      padding: 20px;
      color: #fff;
      box-shadow: 0 4px 12px rgba(var(--primary-color-rgb), 0.3);
      margin-bottom: 20px;
      
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 12px;
        
        span {
          font-size: 16px;
          opacity: 0.9;
        }
      }
      
      .balance-amount {
        margin-bottom: 20px;
        
        .currency {
          font-size: 20px;
          margin-right: 4px;
        }
        
        .amount {
          font-size: 32px;
          font-weight: 600;
        }
      }
      
      .card-actions {
        display: flex;
        justify-content: space-around;
        
        .action-button {
          display: flex;
          flex-direction: column;
          align-items: center;
          background-color: rgba(255, 255, 255, 0.2);
          border-radius: 8px;
          padding: 8px 16px;
          
          .van-icon {
            font-size: 20px;
            margin-bottom: 4px;
          }
          
          span {
            font-size: 14px;
          }
        }
      }
    }
    
    .quick-actions {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 12px;
      margin-bottom: 20px;
      
      .action-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        background-color: var(--background-color-light);
        border-radius: 8px;
        padding: 12px;
        box-shadow: var(--box-shadow);
        
        .van-icon {
          color: var(--primary-color);
          margin-bottom: 8px;
        }
        
        span {
          font-size: 12px;
          color: var(--text-color);
        }
      }
    }
    
    .transaction-section {
      background-color: var(--background-color-light);
      border-radius: 12px;
      padding: 16px;
      box-shadow: var(--box-shadow);
      
      .section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;
        
        span {
          font-size: 16px;
          font-weight: 500;
          color: var(--text-color);
        }
        
        .view-all {
          font-size: 14px;
          color: var(--primary-color);
        }
      }
      
      .transaction-list {
        .transaction-item {
          display: flex;
          align-items: center;
          padding: 12px 0;
          border-bottom: 1px solid var(--border-color-light);
          
          &:last-child {
            border-bottom: none;
          }
          
          .transaction-icon {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 12px;
            color: #fff;
            
            &.icon-recharge {
              background-color: #4CAF50;
            }
            
            &.icon-withdraw {
              background-color: #FF9800;
            }
            
            &.icon-transfer {
              background-color: #2196F3;
            }
            
            &.icon-payment {
              background-color: #F44336;
            }
            
            &.icon-refund {
              background-color: #9C27B0;
            }
          }
          
          .transaction-info {
            flex: 1;
            
            .transaction-title {
              font-size: 16px;
              color: var(--text-color);
              margin-bottom: 4px;
            }
            
            .transaction-time {
              font-size: 12px;
              color: var(--text-color-tertiary);
            }
          }
          
          .transaction-amount {
            font-size: 16px;
            font-weight: 500;
            
            &.amount-positive {
              color: #4CAF50;
            }
            
            &.amount-negative {
              color: #F44336;
            }
          }
        }
      }
    }
  }
  
  .popup-content {
    padding: 16px;
    
    .popup-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-bottom: 16px;
      border-bottom: 1px solid var(--border-color-light);
      
      span {
        font-size: 16px;
        font-weight: 500;
      }
    }
    
    .popup-form {
      margin-top: 16px;
      
      .quick-amounts {
        display: flex;
        flex-wrap: wrap;
        margin: 16px 0;
        
        .amount-tag {
          padding: 8px 16px;
          border-radius: 4px;
          background-color: var(--background-color-light);
          margin-right: 8px;
          margin-bottom: 8px;
          font-size: 14px;
          color: var(--text-color);
          
          &.active {
            background-color: var(--primary-color);
            color: #fff;
          }
        }
      }
      
      .payment-methods, .withdraw-to {
        margin: 16px 0;
        
        .method-title {
          font-size: 14px;
          color: var(--text-color-secondary);
          margin-bottom: 8px;
        }
        
        .payment-method, .bank-card {
          display: flex;
          align-items: center;
          padding: 12px;
          border-radius: 8px;
          background-color: var(--background-color-light);
          margin-bottom: 8px;
          
          &.active {
            border: 1px solid var(--primary-color);
          }
          
          .method-icon, .card-icon {
            width: 24px;
            margin-right: 12px;
            color: var(--primary-color);
          }
          
          .method-name, .card-info {
            flex: 1;
            
            .card-name {
              font-size: 14px;
              color: var(--text-color);
            }
            
            .card-number {
              font-size: 12px;
              color: var(--text-color-tertiary);
            }
          }
          
          .method-check, .card-check {
            color: var(--primary-color);
          }
        }
      }
      
      .withdraw-info {
        background-color: var(--background-color-light);
        border-radius: 8px;
        padding: 12px;
        margin: 16px 0;
        
        .info-item {
          display: flex;
          justify-content: space-between;
          margin-bottom: 8px;
          
          &:last-child {
            margin-bottom: 0;
            padding-top: 8px;
            border-top: 1px dashed var(--border-color-light);
            font-weight: 500;
          }
          
          span {
            font-size: 14px;
            color: var(--text-color);
          }
        }
      }
      
      .popup-actions {
        margin-top: 24px;
      }
    }
    
    .transaction-detail {
      padding: 16px 0;
      
      .detail-amount {
        font-size: 24px;
        font-weight: 600;
        text-align: center;
        margin-bottom: 8px;
        
        &.amount-positive {
          color: #4CAF50;
        }
        
        &.amount-negative {
          color: #F44336;
        }
      }
      
      .detail-status {
        text-align: center;
        margin-bottom: 20px;
      }
      
      .detail-items {
        background-color: var(--background-color-light);
        border-radius: 8px;
        padding: 12px;
        
        .detail-item {
          display: flex;
          justify-content: space-between;
          padding: 8px 0;
          border-bottom: 1px solid var(--border-color-light);
          
          &:last-child {
            border-bottom: none;
          }
          
          .item-label {
            font-size: 14px;
            color: var(--text-color-secondary);
          }
          
          .item-value {
            font-size: 14px;
            color: var(--text-color);
            max-width: 60%;
            text-align: right;
            word-break: break-all;
          }
        }
      }
    }
  }
  
  .empty-state {
    padding: 40px 0;
  }
}
</style> 